package com.sam;


import java.net.Socket;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class SocketService extends Service {

	TCPClient mTcpClient;
	String sessionId = "none";
	Socket socket;
	int i = 0;
	String message = "none";
	SocketService ser = null;
	boolean valueSet = false;
	boolean runFrame = true;
	byte[] frame=null;
	private boolean isPlaying=false;
	public TCPClient getTCPClient() {
		return mTcpClient;
	}

	public String getSessionId() {
		return sessionId;
	}

	synchronized String getMessage() {
		if (!valueSet)
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught");
			}
		System.out.println("Got: " + message);
		valueSet = false;
		notify();
		return message;

	}

	synchronized void putMessage(String message) {
		if (valueSet)
			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("InterruptedException caught");
			}
		this.message = message;
		valueSet = true;
		System.out.println("Put: " + message);
		notify();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("I am in Ibinder onBind method");
		return myBinder;
	}

	private final IBinder myBinder = new LocalBinder();

	// TCPClient mTcpClient = new TCPClient();

	public class LocalBinder extends Binder {
		public SocketService getService() {
			System.out.println("I am in Localbinder ");
			return SocketService.this;

		}
	}

	public int getRandomNumber() {
		return i++;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("I am in on create");
		ser = this;

	}

	public void startTcp() {
		connectTask ob = new connectTask();
		ob.execute("");
	}

	public void IsBoundable() {
		Toast.makeText(this, "I bind like butter", Toast.LENGTH_LONG).show();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		System.out.println("I am in  start");
		
		// Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
		play();

		return START_STICKY;
	}
	
	 @SuppressWarnings("deprecation")
	private void play() {
		    if (!isPlaying) {
		      Log.w(getClass().getName(), "Got to play()!");
		      isPlaying=true;

		      Notification note=new Notification(R.drawable.sam_launcher,
		                                          "SaM Activated",
		                                          System.currentTimeMillis());
		      Intent i=new Intent(this, MainActivity.class);
		      i.putExtra("parameters","main");
		    
		      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
		                 Intent.FLAG_ACTIVITY_SINGLE_TOP);
		    
		      PendingIntent pi=PendingIntent.getActivity(this, 0,
		                                                  i, 0);
		      
		      note.setLatestEventInfo(this, "SaM Server",
		                              "Running",
		                              pi);
		      note.flags|=Notification.FLAG_NO_CLEAR;

		      startForeground(1337, note);
		      
		      startTcp();
		      startLogin();
		      
		    }
		    else if(sessionId.equals("none")){
		    	startLogin();
		    }
		    else{
		    	mTcpClient.sendMessage(new DataStream("login",null,null));
		    }
		    
		   
		  }
	 
	 void startLogin(){
		 Intent i = new Intent();
			i.setClass(ser, LoginActivity.class);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			String[] para = new String[1];
			para[0] = "login";
			i.putExtra("parameters", para);
			startActivity(i);
		 
	 }
	 
	public void stopFrames(){
		 runFrame = false;

		mTcpClient.sendMessage(new DataStream("stoplive",null,null));
	 }
	 
	public class connectTask extends AsyncTask<String, DataStream, TCPClient> {

		@Override
		protected TCPClient doInBackground(String... message) {

			// we create a TCPClient object and
			mTcpClient = TCPClient
					.getInstance(new TCPClient.OnMessageReceived() {
						@Override
						// here the messageReceived method is implemented
						public void messageReceived(DataStream data) {
							// this method calls the onProgressUpdate
							String message = data.getmessage();
							Log.i("message Received", message);
							publishProgress(data);
						}
					});
			mTcpClient.run();

			return null;
		}

		@Override
		protected void onProgressUpdate(DataStream... values) {
			super.onProgressUpdate(values);
			String message = values[0].getmessage();

			Log.i("message", message);

			if (message.equals("sessionId")) {
				
				 Log.i("sessionId",values[0].data[0]);
				
				if (values[0].data[0].equals("none")) {
					Log.i("message contains",values[0].data[0]);
					LoginActivity.la.tv.setText("invalid username or password");
					/*Intent i = new Intent();
					i.setClass(ser, LoginActivity.class);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					//i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
					String[] para = new String[1];
					para[0] = "invalid";
					i.putExtra("parameters", para);
					startActivity(i);
					message = "none";
					values[0].setmessage(message);*/

				} else {
					LoginActivity.la.finish();
					Intent i = new Intent();
					i.setClass(ser, MainActivity.class);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //
					String[] session = new String [1];
					session[0]=values[0].data[0];
					i.putExtra("movies",session);
					sessionId = values[0].data[0];
					startActivity(i);
				}

			}
			if (message.equals("threat")) {
				Intent i = new Intent();
				i.setClass(ser, AlertBox.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //
				startActivity(i);
				

			}
			
			if(message.equals("play")){	 
				
				 Intent i = new Intent();
				 i.setClass(ser,LiveView.class);
				 i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
				 startActivity(i);
				
				/*
				  Intent i = new Intent(); 
				  i.setClass(ser,VideoActivity.class);
				  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
				  String a =values[0].data[0]; 
				  i.putExtra("name",a);
				  message = "none";
				  values[0].setmessage(message); 
				  startActivity(i);
				*/
			}
			
			
			if(message.equals("videoRes"))
			{ message ="none";
			  Log.i("videonames = ",values[0].data[0]); 
			  Intent i = new
			  Intent(); i.setClass(ser,ListViewActivity.class);
			  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
			  String[] a =values[0].data; 
			  i.putExtra("videos",a);
			  values[0].setmessage(message); 
			  startActivity(i);
			}
			
			if(message.equals("frames")){
				LiveView.obj.show(values[0].getimg());
				message="none";
				
			}
			
		

			/*
			 * if(message.equals("videoRes")){ message ="none";
			 * Log.i("videonames = ",values[0].data[0]); Intent i = new
			 * Intent(); i.setClass(ser,ListViewActivity.class);
			 * i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); String[] a
			 * ={"outfile"}; i.putExtra("videos",a);
			 * values[0].setmessage(message); startActivity(i);
			 * 
			 * 
			 * 
			 * }
			 */

			/*
			 * if (message.equals("loginAct")){ DataStream data =new
			 * DataStream("hello",null,null); mTcpClient.sendMessage(data);
			 * 
			 * }
			 * 
			 * 
			 * if (message.equals("byebye")){ DataStream data =new
			 * DataStream("why",null,null); mTcpClient.sendMessage(data);
			 * 
			 * }
			 */

			/*
			 * else if(message.equals("loginAc")){
			 * 
			 * Intent i = new Intent(); i.setClass(ser, AlertBox.class);
			 * i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			 * 
			 * }
			 */

			/*
			 * NotificationManager notificationManager = (NotificationManager)
			 * getSystemService(NOTIFICATION_SERVICE); int icon =
			 * R.drawable.sam_launcher; CharSequence notiText =
			 * "Your notification from the service"; long meow =
			 * System.currentTimeMillis();
			 * 
			 * Notification notification = new Notification(icon,notiText,
			 * meow);
			 * 
			 * Context context = getApplicationContext(); CharSequence
			 * contentTitle = "Your notification"; CharSequence contentText =
			 * "Some data has arrived!"; Intent notificationIntent = new
			 * Intent(ser, VideoActivity.class); PendingIntent contentIntent =
			 * PendingIntent.getActivity(ser, 0, notificationIntent, 0);
			 * 
			 * notification.setLatestEventInfo(context, contentTitle,
			 * contentText, contentIntent);
			 * 
			 * int SERVER_DATA_RECEIVED = 1;
			 * notificationManager.notify(SERVER_DATA_RECEIVED, notification);
			 */
			/*
			 * if (message.equals("threat")) {
			 * 
			 * Intent i = new Intent(); i.setClass(ser, AlertBox.class);
			 * i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); message = "none";
			 * startActivity(i); }
			 */
			/*
			 * image = (ImageView) findViewById(R.id.imageView1);
			 * image.setScaleType(ScaleType.FIT_XY); bmp =
			 * BitmapFactory.decodeByteArray(values[0].getimg(), 0,
			 * values[0].getimg().length); image.setImageBitmap(bmp);
			 */

			/*
			 * if (values[0].getmessage().equals("watch")) { /*
			 * Toast.makeText(getApplicationContext(), "watch video",
			 * Toast.LENGTH_SHORT).show(); Intent intent=new
			 * Intent(MyActivity.this,VideoActivity.class);
			 * startActivity(intent);
			 * 
			 * }
			 */

		}

		
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		try {
			socket.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		socket = null;
	}

}